jQuery(function($) {

var doc = document;
/*鍥剧墖杞挱*/
  var M = {};

  function createElm(text) {
    return doc.createElement(text);
  }

  M.Slide = function() {
    var that = this;
    that.frame = doc.querySelector(".slide");
    that.list = doc.querySelectorAll(".slide .nav li");
    that.images = doc.querySelectorAll(".gallery li");
    that.slideBox = doc.querySelector(".slide");
    that.navBox = doc.querySelector(".slide .nav");
    that.len = that.images.length;
    that.pre = doc.querySelector(".pre");
    that.next = doc.querySelector(".next");
    that.timer = 0;
    that.index = 0;
    
  };
  
  slide = M.slide = new M.Slide();
  
  slide.setIndex = function() {
    var that = this,
        list = doc.querySelectorAll(".gallery li"),
      len = list.length,
      li = null,
      fragment = doc.createDocumentFragment(),
      i = 0;

    for (i; i < len; i++) {
      li = createElm("li");
      
      if (len === 0) {
        li.setAttribute("class", "active");
      } else {
        li.setAttribute("class", "");
      }
      fragment.appendChild(li);
    }


    var nav = doc.querySelector(".nav");
    nav.appendChild(fragment);

    that.list = nav.querySelectorAll("li");

    for (i = 0; i < len; i++) {
        that.list[i].index = i;
    }
  };
  slide.setIndex();
  
  slide.reElement = function(index) {
    var that = this,
      images = that.images,
      len = images.length,
      list = that.list,
      i = 0;
    for (i; i < len; i++) {
      images[i].className = "fadeout";
      list[i].className = "";
    }

    images[index].className = "fadein";
    list[index].className = "active";
  };
  
  slide.eventHandler = function(event) {
    var target = event.target;
    
    if (target.tagName === "LI") {
      slide.index = target.index;
      slide.reElement(target.index);
    }
  };
  
  slide.autoPlay = function() {
    clearInterval(slide.timer);
    slide.timer = setInterval(function() {
      slide.index++;
      if (slide.index >= slide.len) {
        slide.index = 0;
      }
      slide.reElement(slide.index);
    }, 3000);
  };
  slide.autoPlay();
  
  slide.navBox.addEventListener("mouseover", function(event) {
    slide.eventHandler(event);
  }, false);
  
  slide.frame.addEventListener("mouseover", function() {
    clearInterval(slide.timer);
  }, false);
  
  slide.frame.addEventListener("mouseout", function() {
    slide.autoPlay();
  }, false);
  
  slide.pre.addEventListener("click", function() {
    slide.index--;
    if (slide.index < 0) {
      slide.index = slide.len-1;
    }
    slide.reElement(slide.index);
  }, false);
  
  slide.next.addEventListener("click", function() {
    slide.index++;
    if (slide.index >= slide.len) {
      slide.index = 0;
    }
    slide.reElement(slide.index);
  }, false);
});